package com.liuceng.zen.lib.gdt.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.liuceng.zen.common.utils.EncodeUtils;
import com.liuceng.zen.lib.gdt.GdtConstants;

public class GdtUtils {

  public static String buildToken(int uid, String appid, String appkey) {
    String time = "" + (new Date().getTime() / 1000);
    String sign = sha1(StringUtils.join(new String[] {appid, appkey, time}));

    String token = EncodeUtils.base64UrlSafeEncode(
        StringUtils.join(new String[] {"" + uid, appid, time, sign}, ",").getBytes());

    return token;
  }

  public static String buildUrl(String apiUrl, String resourceName, String action) {
    return StringUtils.join(new String[] {apiUrl, resourceName, action}, "/");
  }

  private static String sha1(String input) {
    try {
      MessageDigest mDigest = MessageDigest.getInstance("SHA1");
      byte[] result = mDigest.digest(input.getBytes());
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
      }

      return sb.toString();
    } catch (NoSuchAlgorithmException e) {
      return "";
    }
  }



  public static Integer getCreativeSitesetType(Integer crtSize) {
    if (crtSize == null)
      return null;

    return crtSize == 65 || crtSize == 29 || crtSize == 53 || crtSize == 69 || crtSize == 70
        || crtSize == 71 || crtSize == 88 || crtSize == 120 || crtSize == 137 || crtSize == 184
        || crtSize == 195 || crtSize == 207 || crtSize == 208 || crtSize == 210 || crtSize == 211
        || crtSize == 212 || crtSize == 213 || crtSize == 215 || crtSize == 10 || crtSize == 31
        || crtSize == 35 || crtSize == 28 || crtSize == 59 || crtSize == 58 || crtSize == 79
        || crtSize == 80 || crtSize == 113 || crtSize == 114 || crtSize == 145 || crtSize == 144
        || crtSize == 147 || crtSize == 148 || crtSize == 149 || crtSize == 150 || crtSize == 172
        || crtSize == 181 ? 1 : 0;
  }

  public static Integer getCreativeSitesetType(String[] siteset) {
    if (siteset == null)
      return null;
    String sitesetStr = StringUtils.join(siteset, ",");
    return sitesetStr.contains("_MOBILE_") ? GdtConstants.SITESET_MOBILE : GdtConstants.SITESET_PC;
  }
}


